package com.shijie.log.comparator;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Data
@AllArgsConstructor
public class BigDecimalFieldComparator implements  FieldComparator<BigDecimal> {

    private int scale;

    @Override
    public boolean compare(BigDecimal oldVal, BigDecimal newVal) {
        // 如果两个值相等，返回true
        if (ObjectUtils.nullSafeEquals(oldVal, newVal)) return true;

        // 如果有一个值为null，直接返回false
        if (oldVal == null || newVal == null) return false;

        // 将BigDecimal进行舍入处理
        BigDecimal d1 = oldVal.setScale(scale, RoundingMode.HALF_UP);
        BigDecimal d2 = newVal.setScale(scale, RoundingMode.HALF_UP);

        // 如果相等，返回true；不相等返回false
        return d1.compareTo(d2) == 0;
    }

}